package org.example.src.controller;

import org.example.src.dto.request.CompanyProfileRequest;
import org.example.src.dto.response.ApiResponse;
import org.example.src.dto.response.CompanyProfileResponse;
import org.example.src.entity.Company;
import org.example.src.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/companies")
@CrossOrigin(origins = "*")
public class CompanyController extends BaseController {

    @Autowired
    private CompanyService companyService;

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<Company>> registerCompany(@Valid @RequestBody Company company) {
        Company createdCompany = companyService.createCompany(company);
        return created(createdCompany);
    }

    @GetMapping
    public ResponseEntity<ApiResponse<List<Company>>> getAllCompanies() {
        List<Company> companies = companyService.findAllCompanies();
        return success(companies);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'STUDENT') or (hasRole('COMPANY') and #id == authentication.principal.id)")
    public ResponseEntity<ApiResponse<Company>> getCompanyById(@PathVariable Long id) {
        Company company = companyService.findCompanyById(id);
        if (company == null) {
            return notFound("公司未找到");
        }
        return success(company);
    }

    @GetMapping("/name/{companyName}")
    public ResponseEntity<ApiResponse<Company>> getCompanyByCompanyName(@PathVariable String companyName) {
        Company company = companyService.findCompanyByCompanyName(companyName);
        if (company == null) {
            return notFound("公司未找到");
        }
        return success(company);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN') or (hasRole('COMPANY') and #id == authentication.principal.id)")
    public ResponseEntity<ApiResponse<Company>> updateCompany(@PathVariable Long id, @Valid @RequestBody Company companyDetails) {
        Company updatedCompany = companyService.updateCompany(id, companyDetails);
        if (updatedCompany == null) {
            return notFound("公司未找到");
        }
        return success("公司信息更新成功", updatedCompany);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteCompany(@PathVariable Long id) {
        companyService.deleteCompany(id);
        return noContent();
    }

    @GetMapping("/approval-status/{isApproved}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<List<Company>>> getCompaniesByApprovalStatus(@PathVariable Boolean isApproved) {
        List<Company> companies = companyService.findCompaniesByApprovalStatus(isApproved);
        return success(companies);
    }

    @PutMapping("/{id}/approve")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Company>> approveCompany(@PathVariable Long id) {
        Company approvedCompany = companyService.approveCompany(id);
        if (approvedCompany == null) {
            return notFound("公司未找到");
        }
        return success("公司审核通过", approvedCompany);
    }

    @PutMapping("/{id}/profile")
    @PreAuthorize("hasAnyRole('ADMIN') or (hasRole('COMPANY') and #id == authentication.principal.id)")
    public ResponseEntity<ApiResponse<CompanyProfileResponse>> updateCompanyProfile(@PathVariable Long id, @Valid @RequestBody CompanyProfileRequest request) {
        try {
            CompanyProfileResponse response = companyService.updateCompanyProfile(id, request);
            return success("公司档案更新成功", response);
        } catch (Exception e) {
            return error("更新失败: " + e.getMessage());
        }
    }
}
